<?php if(!empty($subvo)){
    $v = $subvo;
    $subvo = '';
}
if(!empty($subsubvo)){
    $v = $subsubvo;
    $subsubvo = '';
}
?>
<div class="viewBox myBox<?php echo $v['id'];?>" <?php if($_SESSION[C('USER_AUTH_KEY')]){?> sortID="<?php echo $v['sort'];?>" modulesID="<?php echo $v['id'];?>" title="<?php echo $v['title'];?>" deleteUrl="<?php echo U('/Admin/Modules/delete',array('id'=>$v['id']));?>" settingUrl="<?php echo U('/Admin/Modules/edit',array('id'=>$v['id']));?>" isEdit="0"<?php }?>>
  <?php if(!empty($v['dataname'])){
                $v['content'] = $v['dataname'];
                
        }
         ?>
         <div class="panel panel-primary">
    <?php include(TMPL_PATH.'Home/TemplateDefault/Public-Moduletitle'.C('TMPL_TEMPLATE_SUFFIX')); ?>
<div class="panel-body">
<?php if($skuList){?> 

<style type="text/css">
.bh-sku-selected {color: red; background:#fff; border:1px solid #FF0033;}
input{border:1px solid #ccc; border-radius:0px; background:#fff; outline:none; border-radius:2px;}
input[disabled="disabled"]{border:1px solid #ccc; background:#eee; color:#fff;}
</style>

<link type="text/css" rel="stylesheet" href="/sku/css/shCore.css" />
<link type="text/css" rel="stylesheet" href="/sku/css/shCoreDefault.css"/>
<script type="text/javascript" src="/sku/js/json2.js"></script>
<script type="text/javascript" src="/sku/js/shCore.js"></script>
<script type="text/javascript" src="/sku/js/shBrushJScript.js"></script>



<script type="text/javascript">SyntaxHighlighter.all();</script>


<script type="text/javascript">
var startTime = new Date().getTime();
var data;
//销售属性集
$.get('<?php echo U('Ajax/getSKU');?>', {id:<?php echo $id;?>,time:startTime}, function(r){
	data = r;
	setSKU();
},'json');
//后台读取结果集

//保存最后的组合结果信息
var SKUResult = {};
//获得对象的key
function getObjKeys(obj) {
    if (obj !== Object(obj)) throw new TypeError('Invalid object');
    var keys = [];
    for (var key in obj)
        if (Object.prototype.hasOwnProperty.call(obj, key))
            keys[keys.length] = key;
    return keys;
}

//把组合的key放入结果集SKUResult
function add2SKUResult(combArrItem, sku) {
	var key = combArrItem.join(";");
    if(SKUResult[key]) {
        SKUResult[key].count += sku.count;
        SKUResult[key].prices.push(sku.price);
    } else {
        SKUResult[key] = {
            count : sku.count,
            prices : [sku.price]
        };
    }
}

//初始化得到结果集
function initSKU() {
    var i, j, skuKeys = getObjKeys(data);
    for(i = 0; i < skuKeys.length; i++) {
        var skuKey = skuKeys[i];//一条SKU信息key
        var sku = data[skuKey];	//一条SKU信息value
        var skuKeyAttrs = skuKey.split(";"); //SKU信息key属性值数组
		skuKeyAttrs.sort(function(value1, value2) {
			return parseInt(value1) - parseInt(value2);
		});

        //对每个SKU信息key属性值进行拆分组合
		var combArr = combInArray(skuKeyAttrs);
		for(j = 0; j < combArr.length; j++) {
			add2SKUResult(combArr[j], sku);
		}

        //结果集接放入SKUResult
        SKUResult[skuKeyAttrs.join(";")] = {
            count:sku.count,
            prices:[sku.price]
        }
    }
}

/**
 * 从数组中生成指定长度的组合
 * 方法: 先生成[0,1...]形式的数组, 然后根据0,1从原数组取元素，得到组合数组
 */
function combInArray(aData) {
	if(!aData || !aData.length) {
		return [];
	}

	var len = aData.length;
	var aResult = [];

	for(var n = 1; n < len; n++) {
		var aaFlags = getCombFlags(len, n);
		while(aaFlags.length) {
			var aFlag = aaFlags.shift();
			var aComb = [];
			for(var i = 0; i < len; i++) {
				aFlag[i] && aComb.push(aData[i]);
			}
			aResult.push(aComb);
		}
	}
	
	return aResult;
}


/**
 * 得到从 m 元素中取 n 元素的所有组合
 * 结果为[0,1...]形式的数组, 1表示选中，0表示不选
 */
function getCombFlags(m, n) {
	if(!n || n < 1) {
		return [];
	}

	var aResult = [];
	var aFlag = [];
	var bNext = true;
	var i, j, iCnt1;

	for (i = 0; i < m; i++) {
		aFlag[i] = i < n ? 1 : 0;
	}

	aResult.push(aFlag.concat());

	while (bNext) {
		iCnt1 = 0;
		for (i = 0; i < m - 1; i++) {
			if (aFlag[i] == 1 && aFlag[i+1] == 0) {
				for(j = 0; j < i; j++) {
					aFlag[j] = j < iCnt1 ? 1 : 0;
				}
				aFlag[i] = 0;
				aFlag[i+1] = 1;
				var aTmp = aFlag.concat();
				aResult.push(aTmp);
				if(aTmp.slice(-n).join("").indexOf('0') == -1) {
					bNext = false;
				}
				break;
			}
			aFlag[i] == 1 && iCnt1++;
		}
	}
	return aResult;
} 



//初始化用户选择事件
function setSKU() {
	initSKU();
	
	var endTime = new Date().getTime();
	$('#init_time').text('init sku time: ' + (endTime - startTime) + " ms");
	$('.sku').each(function() {
		var self = $(this);
		var attr_id = self.attr('attr_id');
		if(!SKUResult[attr_id]) {
			self.attr('disabled', 'disabled');
		}
	}).click(function() {
		var self = $(this);

		//选中自己，兄弟节点取消选中
		self.toggleClass('bh-sku-selected').siblings().removeClass('bh-sku-selected');
		
		//已经选择的节点
		var selectedObjs = $('.bh-sku-selected');

		if(selectedObjs.length) {
			//获得组合key价格
			var selectedIds = [];
			selectedObjs.each(function() {
				selectedIds.push($(this).attr('attr_id'));
			});
			selectedIds.sort(function(value1, value2) {
				return parseInt(value1) - parseInt(value2);
			});
			var len = selectedIds.length;
			var prices = SKUResult[selectedIds.join(';')].prices;
			var maxPrice = Math.max.apply(Math, prices);
			var minPrice = Math.min.apply(Math, prices);
			$('#price').text(maxPrice > minPrice ? minPrice + "-" + maxPrice : maxPrice.toFixed(2));
			
			$('#price_').text(maxPrice > minPrice ? '--' : (maxPrice.toFixed(2)/<?php echo $discount;?>).toFixed(0));
			
			
			$('#stock').html(SKUResult[selectedIds.join(';')].count);

			//用已选中的节点验证待测试节点 underTestObjs
			$(".sku").not(selectedObjs).not(self).each(function() {
				var siblingsSelectedObj = $(this).siblings('.bh-sku-selected');
				var testAttrIds = [];//从选中节点中去掉选中的兄弟节点

				if(siblingsSelectedObj.length) {
					var siblingsSelectedObjId = siblingsSelectedObj.attr('attr_id');
					for(var i = 0; i < len; i++) {
						(selectedIds[i] != siblingsSelectedObjId) && testAttrIds.push(selectedIds[i]);
					}
				} else {
					testAttrIds = selectedIds.concat();
				}
				testAttrIds = testAttrIds.concat($(this).attr('attr_id'));
				testAttrIds.sort(function(value1, value2) {
					return parseInt(value1) - parseInt(value2);
				});
				if(!SKUResult[testAttrIds.join(';')]) {
					$(this).attr('disabled', 'disabled').removeClass('bh-sku-selected');
				} else {
					$(this).removeAttr('disabled');
				}
			});
		} else {
			//设置默认价格
			$('#price').text('<?php echo $price;?>');
			$('#stock').html('<?php echo $stocks;?>');
			//设置属性状态
			$('.sku').each(function() {
				SKUResult[$(this).attr('attr_id')] ? $(this).removeAttr('disabled') : $(this).attr('disabled', 'disabled').removeClass('bh-sku-selected');
			})
		}
	});
}
</script>







<?php } ?>


<div class="panel panel-default">

        <div class="panel panel-default">
          <h1 style="margin-top:0; padding-top:0.5em; padding-left:0.5em; padding-right:0.5em; font-size:18px;"><?php echo $title;?></h1>
          
          <gt name="supplier_id" value="0">
          <p class="supplier"><?php echo getSupplier($supplier_id); ?></p>
          </gt>
          
          <notempty name="remark">
          <p class="remark"><?php echo $remark; ?></p>
          </notempty>
           
          
          <div style="position:relative;"><p class="price">拼团：<strong style="color: #f00;" >¥<span id="price" style="font-size:24px; font-family:Arial;"><?php echo $isgroup['price']; ?></span></strong>
          
          <!-- 折扣 -->
          
          <gt name="discount" value="0">
             <span style="display:inline-block;">
             
             
             <del style="float:left; margin-left:10px; color:#9A9A9A;">原价：¥<span id="price_"><?php echo $price;?></span></del>
             </span>
             
             
             </gt>
          <!-- 折扣结束 -->
         </p>
         
         
          
          
          
          
            
          
          
          
          <div style="position:absolute; text-align:center; bottom:5px; right:8px;" class="phoneBox"><a href="tel:<?php echo getSysVal('phone'); ?>" class="fa fa-phone" style=" color:#1EA6A8; font-size:32px;">
            
          </a><br>

          <span style="font-size:12px; color:#252525;">客服电话</span></div>
          
          
          
          
          </div>
          
         <div class="panel-footer" style="padding:0; background:#fff;" >
         <?php foreach($skuList as $key => $voattr){?>
         
         <p style="margin-bottom:4px;"></p>
         
          <div class="dgscp-c" style="display:table">
          
          
          <h5 class="bt" style="display:table-cell; min-width:40px;"><strong><?php echo $voattr['title'];?></strong></h5>
          
          
          
          <div style="display:table-cell;"><?php foreach($voattr['list'] as $key => $vattr){?>
          <input class="sku" type="button"  attr_id="<?php echo $vattr['id'];?>" value="<?php echo $vattr['val'];?>" style="margin:5px;"/>
          <?php }?></div>
          
          
          
          </div>
          
          <?php }?>
          
          
          
          
          
          <?php if($skuList){?>
          
          <p style="margin-bottom:10px; border-top:1px solid #CDCDCD; margin-top:5px;"></p>
<?php }else{?>
<div style="height:10px;"></div>
<?php }?>





<div class="dgscp-c" style="display:table; width:100%;"><h5 class="bt" style="display:table-cell; vertical-align:middle; max-width:15px;"><strong style="color:#000;">数量</strong></h5>

<div style="display:table-cell; max-width:40px;">
<div class="input-group input-group-sm">
      <span class="input-group-btn">
        <button style="margin-right:-2px;" class="btn btn-default sub_" type="button">-</button>
      </span>
      <input id="total_" class="form-control cartNum" style="text-align:center; box-shadow:none;" goods_id="<?php echo $cartdata[$key][0];?>" goods_title="<?php echo $cartdata[$key][1];?>" goods_price="<?php echo $cartdata[$key][3];?>" goods_attr="<?php echo $cartdata[$key][4];?>" type="text" name="" value="1">
    
       
      
      <span class="input-group-btn">
        <button class="btn btn-default add_" type="button">+</button>
      </span>
      
      
      
    </div>

</div>





<div class="share" style="display:table-cell; max-width:30px;">

<span style="position:relative; vertical-align:bottom;" onClick="zan();"><i class="fa fa-thumbs-up"></i>
<span id="zannum" style="position:absolute; bottom:15px; right:0; color:#D45356; font-size:12px;">0次</span>
&nbsp;点赞</span>

</div>
<div class="share" style="display:table-cell; max-width:30px;" onClick="showshareBox();">

<i class="fa fa-share-alt"></i>
&nbsp;分享
</div>
</div>
<p style="margin-bottom:5px; border-top:1px solid #CDCDCD; margin-top:10px;"></p>
          </div>
        </div>
      </div>    
<div style="clear:both;"></div>




<?php if($myGrouppurchase){ $alert = '您已经开过团了，不能再拼团购买哦！您可以单买！'; ?>



 

<?php if(count($myGrouppurchase) < $isgroup['capacity']){?>

<div style="position:fixed; z-index:2; background:rgba(255,255,255,0.9); border:1px solid #ccc; border-radius:5px; width:240px; height:140px; top:50%; left:50%; margin-left:-120px; text-align:center; color:#000;">
    <h2 style="margin-bottom:5px; line-height:2em;">您开的团已有<span style="color:#f00;"><?php echo count($myGrouppurchase);?></span>人购买<br>
<span style="font-size:11px; color:#f00;">(马上分享到朋友圈或者微信群邀请朋友参团)</span></h2>
<a href="javacript:void(0);" onClick="$(this).parent().remove();" class="btn btn-warning">我知道</a>
</div>
 

<?php }?>


 




<ul id="timeoutcountdown" class="countdown<?php echo $v['id'];?>">
<li>活动</li>
  <li> <span class="days">00</span>
   
  </li>
  <li class="seperator">天</li>
  <li> <span class="hours">00</span>
    
  </li>
  <li class="seperator">小时</li>
  <li> <span class="minutes">00</span>
  </li>
  <li class="seperator">分钟</li>
  <li> <span class="seconds">00</span>
    <li class="seperator">秒</li>
  </li>
  <li>后结束</li>
</ul>

<script type="text/javascript">
	$('.countdown<?php echo $v['id'];?>').downCount({
		date:<?php echo strtotime($isgroup['end_time']); ?>,
		offset: +10,
		cur_time:<?php echo time();?>
	}, function () {
		alert('活动结束!');
	});
</script>

<div class="page-header" style="margin-top:0; padding-bottom:0;">
  <h2 style="margin-bottom:5px;">您开的团已有<?php echo count($myGrouppurchase);?>人购买<span style="font-size:12px; color:#f00;">(马上分享到朋友圈邀请朋友购买)</span></h2>
</div>
    <div class="row">

<?php foreach($myGrouppurchase as $key => $vo){?>

  <div class="col-sm-2 col-md-2 col-xs-2">
    <div class="thumbnail" style="border:none;">
      <img style="border-radius:100px;" src="<?php echo $vo['img_url'];?>" alt="...">
      <div class="caption" style="padding:5px; text-align:center;">
        <h3 style="margin:0; font-weight:normal; font-size:9px; height:9px; overflow:hidden; padding:0; line-height:1;"><?php echo $vo['nickname'];?></h3>
      </div>
    </div>
  </div>

<?php }?>
</div>


<?php }?>


<?php if($Grouppurchase){ $alert = '您已经参与拼团了，不能再拼团购买哦！您可以单买！'; ?>
<div class="page-header" style="margin-top:0; padding-bottom:0;">
  <h2 style="margin-bottom:5px;">您参与的团已有<?php echo count($Grouppurchase);?>人购买</h2>
</div>
    <div class="row">

<?php foreach($Grouppurchase as $key => $vo){?>

  <div class="col-sm-2 col-md-2 col-xs-2">
    <div class="thumbnail" style="border:none;">
      <img style="border-radius:100px;" src="<?php echo $vo['img_url'];?>" alt="...">
      <div class="caption" style="padding:5px; text-align:center;">
        <h3 style="margin:0; font-weight:normal; font-size:9px; height:9px; overflow:hidden; padding:0; line-height:1;"><?php echo $vo['nickname'];?></h3>
      </div>
    </div>
  </div>

<?php }?>
</div>


<?php }?>







<!-- 下方按钮 -->

<div id="successBox" style="position:fixed; left:50%; top:50%; text-align:center; padding:10px; border-radius:5px;color:#fff; background:#000000; margin-left:-60px; margin-top:-30px; width:120px; display:none; z-index:3000;">
<p style="margin-bottom:0;"><i class="fa fa-check-circle-o"></i></p>
加入成功
</div>

<div class="row cartButton" style="position:fixed; bottom:0; width:0; left:0; width:100%; background:#fff; z-index:200;">
<div class="col-xs-2 col-sm-2 col" style="text-align:center; line-height:18px; border-top:1px solid #E8E8E8;" onClick="window.location.href='<?php echo U('Cart/index');?>'">

<div style="height:3px;"></div>
<i style="font-size:2em; z-index:2; position:relative; margin-left:-5px; padding-top:0.1em;" class="fa fa-shopping-cart">
<!-- 购物车提示 -->
<div id="gotoCart" style="position:absolute; padding:8px; bottom:50px; background:rgba(208,61,63,0.8); z-index:201; min-width:110px; border-radius:4px; display:none !important;">
    <p style="color:#fff; font-size:0.5em; margin-bottom:3px;">成功加入购物</p>
    <a href="<?php echo U('Cart/index');?>" class="btn btn-danger btn-sm" style="font-size:0.5em; height:24px; line-height:24px; border:rgba(255,255,255,0.8);">去结算</a>
    <span style="position:relative; display:block; color:rgba(0,0,0,1.00)">
    <i style="position:absolute; left:0; margin-top:-2px; top:10px; border-top:10px solid rgba(208,61,63,0.8); border-left:10px solid rgba(116,9,11,0.00); border-right:10px solid rgba(116,9,11,0.00);"></i>
    </span>
</div>
<!-- -->

<span style="position:absolute; display:none !important; top:0px; right:-8px; border-radius:10px; line-height:16px; background:#f60; color:#fff; padding:3px; font-size:10px; font-family:Arial; width:20px; height:20px;" id="cartNum"></span></i>
<p style="font-size:0.8em; margin-bottom:0; color:#AAAAAA; line-height:1;">购物车</p>
</div>
    <div class="col-xs-5 col-sm-5 col"><a href="javascript:void(0);" onclick="addCart();" class="btn btn-warning addCartButton" style="display:block; border-radius:0;" >单买<span style="font-size:12px;">(¥<?php echo $price;?>)</span></a></div>
    
    
    
    
    <div class="col-xs-5 col-sm-5 col"><a href="javascript:void(0);" onClick="<?php if($myGrouppurchase){?>alert('您已经参与了拼团，您可以单独购买！');<?php }else{?>addCart_quick();<?php }?>" class="btn btn-danger addCartButtonQuick" style="border-radius:0; display:block;" >拼团购买<span style="font-size:12px;">(<?php echo $isgroup['capacity'];?>人团)</span></a></div>
    
    
    

    
</div>


<!-- 下方按钮结束 -->
       
 <div style="clear:both"></div>      
       
       
       <?php if(strtolower(GROUP_NAME) != 'admin'){?>
       
       
<script>

$('.add_').click(function(e) {
	var val = $(this).parent().prev('input').eq(0).val()*1;
	$(this).parent().prev('input').eq(0).val(val + 1);
	
	
});
$('.sub_').click(function(e) {
    var val = $(this).parent().next('input').eq(0).val()*1;
	if(val > 1){
		$(this).parent().next('input').eq(0).val(val - 1);
	}
});

	function addCart(){
		var attr = new Array();
		$('.bh-sku-selected').each(function(index, element) {
            attr.push($(this).attr('attr_id'));
        });
		$.ajax({
			url:"<?php echo U('Cart/insert');?>",
			data:"cart=1&title=<?php echo $title;?>&id=<?php echo $goods_id;?>:"+attr.join(';')+"&total="+$('#total_').val()+"&price="+$('#price').html(),
			type:'POST',
			dataType:"html",
			success: function(data){
				if(data > 0){
					updateCartNum();
					var successBox = $('#successBox');
					successBox.show();
					successBox.animate({opacity:0.8},'','',function(){
						setTimeout(function(){successBox.hide();successBox.css({opacity:0});},500);
					});
					$('#gotoCart').show();
					//success('成功加入购物车');
				}else{
					error(data);
				}
			}
		});
	}
	
	function addCart_quick(){
		var attr = new Array();
		$('.bh-sku-selected').each(function(index, element) {
            attr.push($(this).attr('attr_id'));
        });
		$.ajax({
			url:"<?php echo U('Cart/insert');?>",
			data:"grouppurchase<?php echo $goods_id;?>:"+attr.join(';')+"=1&cart=1&title=<?php echo $title;?>&id=<?php echo $goods_id;?>:"+attr.join(';')+"&total="+$('#total_').val()+"&price="+$('#price').html(),
			type:'POST',
			dataType:"html", 
			success: function(data){
				if(data > 0){
					location.href = '<?php echo U('Cart/index',array('isLogin' => 1));?>';
				}else{
					error(data);
				}
			}
		});
	}
	
	function updateCartNum(){
		$.post('<?php echo U('Cart/getCount');?>?'+new Date().getTime(), {}, function(data){
			$('#cartNum').html(data);
			
			$('#cartNum').animate({'font-size':'12px','font-weight':'bold'},'','',function(){
				$('#cartNum').animate({'font-size':'10px','font-weight':'normal'});
			});
			$('#cartNum').show(100);
		},'html');
	}
	 
	$(document).ready(function(e) {
		
	    setInterval(function(){
			$.get('<?php echo U('Home/Ajax/GrouppurchaseSale');?>', {'product_id':<?php echo $id;?>}, function(data){
				//alert(data);
				$(document.body).append('<div class="ajaxsale" style="position:fixed; top:50px; left:10px; background:rgba(0,0,0,0.68); color:#fff; font-size:10px; border-radius:10px; padding:2px 5px;">'+data+'刚刚下单</div>');
				
				setTimeout(function(){
					$('.ajaxsale').animate({opacity:0},'','',function(){
						$('.ajaxsale').remove();
					});
				},2000);
			},'html');
		},20000);
		
		
		
		$(document.body).append('<div style="height:50px;">&nbsp;</div>');
        updateCartNum();
		/* 库存和销量 */
		$.get('<?php echo U('Ajax/getStockAndSale');?>',{id:<?php echo $id;?>},function(data){
			$('#saleBox').html(data.sale);
			$('#stock').html(data.stock);
			$('#zannum').html(data.zan+'次');
		},'json');
    });
	
	function zan(){
		$.get('<?php echo U('Ajax/ProductZan');?>', {id:<?php echo $id;?>}, function(data){
			if(data.status == 1){
				$('#zannum').html(data.data+'次');
			}else{
				error(data.info);
			}
		},'json');
	}
</script>
<?php }?>


</div>
</div></div>